#!/usr/bin/env python
# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

import os
import logging
import tarfile
from lxml import etree

logger = logging.getLogger('build_wcp')
hdlr = logging.FileHandler('build_wcp.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

def cleanup(cwd):
    #os.system("rm -fR /tmp/build_ /tmp/wine*")
    os.chdir(cwd)

for filename in os.listdir("incoming/"):
    if os.path.isdir("incoming/"+filename):
        logger.info("Building: "+filename)
        print "Building: "+filename
        cwd = os.getcwd()
        try:
            os.chdir("incoming/"+filename+"/data")
        except:
            logger.debug("Not a WineCellar package: "+filename)
            continue
        
        logger.info("Building: "+filename)
        print "Building: "+filename
        logger.info("Compressing data for "+filename)
        print "Compressing data for "+filename
        code = os.system("tar -cjf ../data.tar.bz2 *")
        if code != 0:
            logger.error("Failed compressing data for "+filename)
            print "Failed compressing data for "+filename
            os.system("rm -f ../data.tar.bz2")
            cleanup(cwd)
            continue
        else:
            logger.info("Compressing data finished for "+filename)
            print "Compressing data finished for "+filename
            
        os.chdir(cwd+"/incoming/"+filename)
            
        code = os.system("rm -fR data")
        if code != 0:
            logger.error("Failed compressing data for "+filename)
            print "Failed compressing data for "+filename
            cleanup(cwd)
            continue
            
        logger.debug("Reading control.xml for "+filename)
        try:
            parser = etree.XMLParser(remove_blank_text=True)
            tree = etree.parse(str("control.xml"), parser)
        except:
            logger.error("Error reading control.xml for "+filename)
            print "Error reading control.xml for "+filename
            cleanup(cwd)
            continue
              
        for element in tree.iter("Wine"):
            name = element.find("name").text
            logger.debug("Wine package")
            break
        else:
            for element in tree.iter("Application"):
                name = element.find("shortname").text
                logger.debug("Application package")
                break
            else:
                logger.error("Corrupt control.xml for "+filename)
                print "Corrupt control.xml for "+filename
                cleanup(cwd)
                continue

        version = tree.find("version").text
        logger.debug("Found name: "+name+" Found version: "+version)
        
        logger.info("Creating package for "+filename)
        print "Creating package for "+filename
        code = os.system("tar -cf "+cwd+"/packages/"+name+"-"+version+".wcp *")
        if code != 0:
            logger.error("Failed Creating package for "+filename)
            print "Failed Creating package for "+filename
            cleanup(cwd)
            continue
        else:
            logger.info("Creating package finished for "+filename)
            print "Creating package finished for "+filename
            cleanup(cwd)
            os.system("rm -fR incoming/"+filename)
